//
//  BDSearchResultViewController.m
//  BadBoy
//
//  Created by wen on 2017/3/28.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDSearchResultViewController.h"
#import "BDUserModel.h"
#import "DOPDropDownMenu.h"
#import "BDShopTableViewCell.h"
#import "BDShopModel.h"
#import "BDShopInfoDeatilViewController.h"
#import "BDLocationServer.h"
@interface BDSearchResultViewController ()<DOPDropDownMenuDataSource, DOPDropDownMenuDelegate, UITableViewDelegate, UITableViewDataSource>
{
    NSArray *_typeArray;
    NSArray *_areaArray;
    NSArray *_sortArray;
    
    NSInteger _currentType;
    NSInteger _currentAreaIndex;
    NSInteger _currentSort;
}
@property (nonatomic, strong) DOPDropDownMenu *menu;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *datasource;

@end

@implementation BDSearchResultViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"搜索结果";
    
    _datasource = [NSMutableArray array];
    
    _currentSort = 0;
    _currentAreaIndex = 0;
    NSString *currentType = [[NSUserDefaults standardUserDefaults] objectForKey:@"shopAndPostType"];
    _currentType = [_typeArray indexOfObject:currentType];
    
    _sortArray = @[@"智能排序", @"评价最高", @"距离最近", @"价格最低"];
    _areaArray = @[@"1 km",@"3 km",@"5 km",@"10 km", @"15 km"];
    _typeArray = @[@"全部", @"水疗", @"KTV", @"夜总会", @"酒吧", @"沐足", @"其他"];
    self.menu = [[DOPDropDownMenu alloc] initWithOrigin:CGPointMake(0, kBDTopHeight) andHeight:44];
    _menu.delegate = self;
    _menu.dataSource = self;
    [self.view addSubview:_menu];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.startPage = @"1";
        [self requestData];
    }];
    [self.tableView.mj_header beginRefreshing];
}

- (void)requestData{
    BDLocationModel *model = [BDLocationModel getLocationInfo];
    NSString *city_id = [BDLocationServer getCurrentCity_id];
    NSString *url = [NSString stringWithFormat:@"%@shops?page=%@&size=%@&type=%zd&order=%zd&user_lng=%f&user_lat=%f&user_city_id=%@", KBDBaseURL, self.startPage, self.pageSize, _currentType, _currentSort + 1, model.longitude, model.latitude, city_id];
    
    //区域和距离
    NSString *disString = _areaArray[_currentAreaIndex];
    url = [url stringByAppendingString:[NSString stringWithFormat:@"&distance=%@", [disString componentsSeparatedByString:@" "].firstObject]];
    //关键字
    if (self.keyword != nil) {
        url = [url stringByAppendingString:[NSString stringWithFormat:@"&keyword=%@", self.keyword]];
    }
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self requestWithUrl:url];
}

- (void)requestWithUrl:(NSString *)url{
    
    NSString *headValid = [BDUserModel getHeaderValidation];
    BDLog(@"当前发现的url是：%@", url);
    RACCommand *command = [BDNetworkingServer v2_GET:url parameters:nil validation:headValid automaticProcessingError:YES];
    RACSignal *signal = [command execute:nil];
    
    [signal subscribeNext:^(id  _Nullable x) {
        if ([_tableView.mj_header isRefreshing]) {
            [_datasource removeAllObjects];
            [_tableView.mj_header endRefreshing];
        }
        if ([_tableView.mj_footer isRefreshing]) {
            [_tableView.mj_footer endRefreshing];
        }
        NSArray *array = x[@"list"];
        [self.datasource addObjectsFromArray:[BDShopModel mj_objectArrayWithKeyValuesArray:array]];
        [self.tableView reloadData];
        self.isEnd = [x[@"is_end"] boolValue];
        self.startPage = x[@"next_page"];
        self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            [self requestData];
        }];
        [self setTableiewFooterViewStateFor:self.tableView datasourceCount:self.datasource.count];
    }];
    
    [signal subscribeError:^(NSError * _Nullable error) {
        BDLog(@"请求数据失败");
    }];
}


#pragma mark -----------------------dropMenu代理-------------------------------
//标题个数
- (NSInteger)numberOfColumnsInMenu:(DOPDropDownMenu *)menu{
    return 3;
}

//每个标题对应的行数
- (NSInteger)menu:(DOPDropDownMenu *)menu numberOfRowsInColumn:(NSInteger)column{
    switch (column) {
        case 0:
            return _areaArray.count;
            break;
        case 1:
            return _typeArray.count;
            break;
        case 2:
            return _sortArray.count;
            break;
        default:
            break;
    }
    return 0;
}

//每个标题对应行的内容
- (NSString *)menu:(DOPDropDownMenu *)menu titleForRowAtIndexPath:(DOPIndexPath *)indexPath{
    switch (indexPath.column) {
        case 0:
            return _areaArray[indexPath.row];
            break;
        case 1:
            return _typeArray[indexPath.row];
            break;
        case 2:
            return _sortArray[indexPath.row];
            break;
        default:
            break;
    }
    return nil;
}

//- (NSInteger)menu:(DOPDropDownMenu *)menu numberOfItemsInRow:(NSInteger)row column:(NSInteger)column{
//    if (column == 0) {
//        if (row == 0) {
//            return _areaDistantArray.count;
//        }else if (row == 1) {
//            return _areaDistrictArray.count;
//        }
//    }
//    return 0;
//}
//
//- (NSString *)menu:(DOPDropDownMenu *)menu titleForItemsInRowAtIndexPath:(DOPIndexPath *)indexPath{
//    if (indexPath.column == 1) {
//        if (indexPath.row == 0) {
//            return _areaDistantArray[indexPath.item];
//        }else if (indexPath.row == 1) {
//            return _areaDistrictArray[indexPath.item];
//        }
//    }
//    return nil;
//}

//点击事件
- (void)menu:(DOPDropDownMenu *)menu didSelectRowAtIndexPath:(DOPIndexPath *)indexPath{
    switch (indexPath.column) {
        case 0:
            _currentAreaIndex = indexPath.row;
            break;
        case 1:
            _currentType = indexPath.row;
            break;
        case 2:
            _currentSort = indexPath.row;
            break;
            
        default:
            break;
    }
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark ----------------------------tableview代理-------------------------------------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.datasource.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 90;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BDShopTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"resCell" forIndexPath:indexPath];
    BDShopModel *shopModel = self.datasource[indexPath.row];
    [cell configeWithModel:shopModel index:indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    BDShopInfoDeatilViewController *bussinessVC = [[BDShopInfoDeatilViewController alloc]init];
    bussinessVC.hidesBottomBarWhenPushed = YES;
    //商家id
    BDShopModel *shopModel = self.datasource[indexPath.row];
    bussinessVC.shopID = [NSString stringWithFormat:@"%zd", shopModel.shop_id];
    bussinessVC.title = shopModel.title;
    [self.navigationController pushViewController:bussinessVC animated:YES];
}

- (UITableView *)tableView{
    if (!_tableView) {
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, self.menu.bottom, kBDScreenWidth, kBDScreenHeight - self.menu.bottom) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [[UIView alloc] init];
        [_tableView registerClass:[BDShopTableViewCell class] forCellReuseIdentifier:@"resCell"];
        _tableView.backgroundColor = [UIColor clearColor];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

